package com.oxy.action.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

import com.oxy.util.Oxy;

public final class I18nUtil {
	private static I18nUtil inst = null;
	
	private static Locale locale = null;
	private static List<ResourceBundle> defResBundle = null;
	
	private I18nUtil(){
		init();
	}
	
	private static synchronized void init(){
		try {
			String strutsCfgFile = Oxy.getCfgManager().App().CFG_STRUTS;
			File file = new File(strutsCfgFile);
			FileReader fr = new FileReader(file);
			Properties prop = new Properties();
			prop.load(fr);
			String strutsLocale = Oxy.getCfgManager().Struts().LOCALE;
			if(strutsLocale==null || strutsLocale.equals("")){
				locale = Locale.getDefault();
			}
			else{
				locale = new Locale(strutsLocale);
			}
			String resPath = Oxy.getCfgManager().Struts().I18N_RESOURCE.trim();
			String[] strArr = resPath.split(",");
			
			defResBundle = new ArrayList<ResourceBundle>();
			for(String item:strArr){
				defResBundle.add(ResourceBundle.getBundle(item.trim(), locale));
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static I18nUtil getInstance(){
		if(inst == null){
			inst = new I18nUtil();
		}
		return inst;
	}
	
	public static List<ResourceBundle> getResBundles(){
		return getInstance().defResBundle;
	}
	public static ResourceBundle getResBundle(String resNm){
		return ResourceBundle.getBundle(resNm, getInstance().locale);
	}
	public static ResourceBundle getResBundle(String resNm, Locale loc){
		return ResourceBundle.getBundle(resNm, loc);
	}
	
	public static String getString(String key){
		String ret=null;
		for(ResourceBundle item : getInstance().defResBundle){
			try{
				ret = item.getString(key);
			}catch(Exception e){
				ret = null;
			}
			
			if(ret != null){
				break;
			}
		}
		return ret;
	}
	public static String getString(String resNm, String key){
		return ResourceBundle.getBundle(resNm, getInstance().locale).getString(key);
	}
	public static String getString(String resNm, Locale loc, String key){
		return ResourceBundle.getBundle(resNm, loc).getString(key);
	}
	
	public static void main(String args[]){
		System.out.println(I18nUtil.getString("member.register.namecantbenull"));
	}
}
